package online.flowerinsnow.minecraft.bukkit.testffa.stats;

import online.flowerinsnow.minecraft.bukkit.testffa.Main;
import online.flowerinsnow.minecraft.bukkit.testffa.core.TestFFACore;
import online.flowerinsnow.minecraft.bukkit.testffa.manager.SQLManager;
import online.flowerinsnow.minecraft.bukkit.testffa.manager.ScoreboardManager;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.UUID;

public class PlayerStatsImpl implements IPlayerStats {
    @NotNull public final UUID uuid;
    private int kill;
    private int death;

    public PlayerStatsImpl(@NotNull UUID uuid, int kill, int death) {
        this.uuid = uuid;
        this.kill = kill;
        this.death = death;
    }

    @Override
    public @NotNull UUID getUUID() {
        return uuid;
    }

    @Override
    public int getKill() {
        return kill;
    }

    @Override
    public int getDeath() {
        return death;
    }

    @Override
    public void setKill(int kills) {
        kill = kills;
        Player player = Bukkit.getPlayer(uuid);
        if (player.isOnline()) {
            ScoreboardManager.setLineSuffix(player, 8, "§f" + kills);
            ScoreboardManager.setLineSuffix(player, 6, "§f" + String.format("%.2f", (double) kills / (double) death));
        }
        try (Statement statement = SQLManager.getConnection().createStatement()) {
            statement.executeUpdate("UPDATE `ffastats` SET `kill` = " + kills + " WHERE `uuid` = '" + getUUID().toString() + "'");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setDeath(int deaths) {
        death = deaths;
        Player player = Bukkit.getPlayer(uuid);
        if (player.isOnline()) {
            ScoreboardManager.setLineSuffix(player, 7, "§f" + deaths);
            ScoreboardManager.setLineSuffix(player, 6, "§f" + String.format("%.2f", (double) kill / (double) deaths));
        }
        try (Statement statement = SQLManager.getConnection().createStatement()) {
            statement.executeUpdate("UPDATE `ffastats` SET `death` = " + deaths + " WHERE `uuid` = '" + getUUID().toString() + "'");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setKillAsync(int kills) {
        Bukkit.getScheduler().runTaskAsynchronously(Main.getInstance(), () -> setKill(kills));
    }

    @Override
    public void setDeathAsync(int deaths) {
        Bukkit.getScheduler().runTaskAsynchronously(Main.getInstance(), () -> setDeath(deaths));
    }
}
